package com.baseweb.webadmin.controller.api;

import com.baseweb.webadmin.controller.BaseController;
import com.baseweb.webadmin.core.constants.BaseState;
import com.baseweb.webadmin.core.constants.UserType;
import com.baseweb.webadmin.core.model.bvo.UpdateBvo;
import com.baseweb.webadmin.core.model.pojo.ByUserBizSchedule;
import com.baseweb.webadmin.core.model.pojo.ByUserExample;
import com.baseweb.webadmin.core.model.pojo.ByUserExampleDetail;
import com.baseweb.webadmin.core.model.pojo.User;
import com.baseweb.webadmin.core.util.*;
import com.baseweb.webadmin.service.*;
import net.sf.json.JSONObject;
import org.apache.ibatis.annotations.Update;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
@RequestMapping(value = "/api/common/")
public class ApiCommonController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(ApiUserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private UserOrderService userOrderService;

    @ResponseBody
    @RequestMapping(value = "/cities", method = RequestMethod.GET)
    public Map<String, Object> cities() {

        return success(userService.selectAllCities());
    }

    /**
     * 发送注册验证码
     *
     * @param mobile
     *            手机号码
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "sendValidMsg", method = RequestMethod.POST)
    public void sendValidMsg(@RequestParam(value = "mobile", defaultValue = "") String mobile,
                             HttpServletRequest request, HttpServletResponse response) {

        // 将数据放入到内存
        if (mobile == null) {
            fail("手机号码不能为空！");
        }
        String code = CheckCodeUtil.newCheckCode(mobile);
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        map.put("code", code);
        map.put("product", ConfigUtil.getSmsFreeSignName());
        boolean flag = CommonUtil.sendMessage(mobile, JSONObject
                .fromObject(map).toString(), ConfigUtil
                .getSmsTemplateCodeRegist());
        if (flag) {
            success("短信发送成功");
        } else {
            fail("短信发送失败");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getUserSchedulesList", method = RequestMethod.GET)
    public Map<String, String> cities(@RequestParam(value = "user_id", required = true) Integer user_id,
                                      @RequestParam(value = "year", required = true) Integer year,
                                      @RequestParam(value = "month", required = true) Integer month) {

        DateTime currentDt = new DateTime();

        DateTime startTime = new DateTime(year, month, 1, 0, 0, 0);

        DateTime endTime = startTime.plusMonths(1);

        List<ByUserBizSchedule> scheduleList = null;

        Map<String, String> map = new HashMap<String, String>();

        User user = userService.selectUserById(user_id);

        if (user.getUserType().intValue() == UserType.TEAM_BIZ.getCode()){
            scheduleList = userOrderService.selectScheduleListByPage(user_id,BaseState.DELETE.getCode(),startTime, endTime,0,Integer.MAX_VALUE);

            if (scheduleList != null && scheduleList.size() > 0){
                for (ByUserBizSchedule current : scheduleList){
//                    Map map = new HashMap();
                    map.put(DateUtil.dateToString(current.getScheduleDate(), "yyyyMMdd"),"greyClass");
//                    result.add(map);
                }
            }
        }else{
            scheduleList = userOrderService.selectScheduleListByPage(user_id,null,startTime, endTime,0,Integer.MAX_VALUE);

            if (scheduleList != null && scheduleList.size() > 0){
                Set set = new HashSet();
                for (ByUserBizSchedule current : scheduleList){
//                    Map map = new HashMap();
                    String dateStr = DateUtil.dateToString(current.getScheduleDate(), "yyyyMMdd");
                    if (current.getStatus().intValue() == BaseState.DELETE.getCode()){
                        map.put(dateStr,"greyClass");
//                        result.add(map);
                    }else{
                        if (set.contains(dateStr)){
                            map.put(dateStr,"redClass");

//                            result.add(map);
                        }else{
                            set.add(dateStr);
                        }

                    }
                }
            }
        }

        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/biz_example", method = RequestMethod.GET)
    public Map<String, Object> biz_example(@RequestParam(value = "example_id", required = false) Integer example_id,
                                           Model model) {

        List<Map<String, String>> imgList= new ArrayList<Map<String, String>>();

        List<ByUserExampleDetail> list = userService.selectExampleDetailListByPage(null, example_id, null, 0, Integer.MAX_VALUE);

        if (list != null && list.size() > 0){
            for (ByUserExampleDetail current : list){
                Map map = new HashMap();
                map.put("src", "http://img.boyitongcheng.com/"+current.getImgUrl()+"!1024x800");
                map.put("w","1048");
                map.put("h","696");
                map.put("title",current.getName());
                imgList.add(map);
            }
        }else{
            ByUserExample byUserExample = userService.findExample(example_id);
            Map map = new HashMap();
            map.put("src", "http://img.boyitongcheng.com/"+byUserExample.getImgUrl()+"!1024x800");
            map.put("w","1048");
            map.put("h","696");
            map.put("title",byUserExample.getName());
            imgList.add(map);
        }

//        try {
//            model.addAttribute("imgList", new ObjectMapper().writeValueAsString(imgList));
//        } catch (IOException e) {
//            model.addAttribute("imgList", "");
//        }

        return success(imgList);
    }


    @ResponseBody
    @RequestMapping(value = "/updateVersion", method = RequestMethod.POST)
    public Map<String, Object> updateVersion(@RequestParam(value = "cilentOs", required = false) String cilentOs,
                                              @RequestParam(value = "cilentVersion", required = false) String cilentVersion,
                                              @RequestParam(value = "cilentType", required = false) String cilentType) {
//        UpdateBvo updateBvo = new UpdateBvo();
//        updateBvo.setCheckStatus(1);
//        if (cilentOs.equalsIgnoreCase("android")) {
//            updateBvo.setUpdateUrl("http://img.boyitongcheng.com/BoyiApp.apk");
//        }
//        updateBvo.setVersionDescribe("新版本升级!");
//
//        return success(updateBvo);

        return fail("当前为最新版本!");
    }
}
